package com.zhbcm.websocketstudy.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/3/9 22:37
 */
@Component
@ServerEndpoint(value = "/socket")
@Slf4j
public class WebSocketService
{
    private Session session;
    private String flag;
    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的.
    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    // 使用线程安全的集合CopyOnWriteArraySet
    private static CopyOnWriteArraySet<WebSocketService> websocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session)
    {
        this.session = session;
        websocketSet.add(this);
        log.info("一个客户端连接进来了,他的sessionId是:{}", session.getId());
        addOnlineCount(); //在线数加1
        log.info("当前在线人数为: {}", getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message)
    {
        try
        {
            this.sendMessage(message);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void sendMessage(String message) throws IOException
    {
        for (WebSocketService webSocketService : websocketSet)
        {
            webSocketService.session.getBasicRemote().sendText(message);
        }
    }

    @OnClose
    public void OnClose(Session session, CloseReason closeReason)
    {
        websocketSet.remove(this);
        log.info("一个客户端关闭了,他的sessionId是: {}", session.getId());
        //从set中删除
        subOnlineCount();
        log.info("当前在线人数为: {}", getOnlineCount());
    }

    @OnError
    public void onError(Throwable t)
    {
        t.printStackTrace();
    }

    public static int getOnlineCount()
    {
        return atomicInteger.get();
    }

    public static void addOnlineCount()
    {
        atomicInteger.incrementAndGet();
    }

    public static void subOnlineCount()
    {
        atomicInteger.decrementAndGet();
    }
}
